<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryRef" :inline="true" :model="queryParams" label-width="68px">
      <el-form-item label="仓库ID" prop="warehouseId">
        <el-input
            v-model="queryParams.warehouseId"
            clearable
            placeholder="请输入仓库ID"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="盘点人" prop="userId">
        <el-input
            v-model="queryParams.userId"
            clearable
            placeholder="请输入盘点人"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="state">
        <el-input
            v-model="queryParams.state"
            clearable
            placeholder="请输入状态"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="更新时间" style="width: 308px">
        <el-date-picker
            v-model="daterangeUpdateTime"
            end-placeholder="结束日期"
            range-separator="-"
            start-placeholder="开始日期"
            type="daterange"
            value-format="YYYY-MM-DD"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button icon="Search" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            v-hasPermi="['wms:stockCheck:add']"
            icon="Plus"
            plain
            type="primary"
            @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            v-hasPermi="['wms:stockCheck:edit']"
            :disabled="single"
            icon="Edit"
            plain
            type="success"
            @click="handleUpdate"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            v-hasPermi="['wms:stockCheck:remove']"
            :disabled="multiple"
            icon="Delete"
            plain
            type="danger"
            @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            v-hasPermi="['wms:stockCheck:export']"
            icon="Download"
            plain
            type="warning"
            @click="handleExport"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="stockCheckList" @selection-change="handleSelectionChange">
      <el-table-column align="center" type="selection" width="55"/>
      <el-table-column align="center" label="事务ID" prop="id"/>
      <el-table-column align="center" label="仓库ID" prop="warehouseId"/>
      <el-table-column align="center" label="盘点人" prop="userId"/>
      <el-table-column align="center" label="状态" prop="state">
      <template #default="scope">
        <dict-tag :options="sys_state" :value="scope.row.state"/>
      </template>
      </el-table-column>
      <el-table-column align="center" label="备注" prop="remark"/>
      <el-table-column align="center" label="创建者" prop="createBy"/>
      <el-table-column align="center" label="入库时间" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="更新者" prop="updateBy"/>
      <el-table-column align="center" label="更新时间" prop="updateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" class-name="small-padding fixed-width" fixed="right" label="操作" width="180">
        <template #default="scope">
          <el-button v-hasPermi="['wms:stockCheck:edit']" icon="Edit" link type="primary"
                     @click="handleUpdate(scope.row)">修改
          </el-button>
          <el-button v-hasPermi="['wms:stockCheck:remove']" icon="Delete" link type="primary"
                     @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        v-model:limit="queryParams.pageSize"
        v-model:page="queryParams.pageNum"
        :total="total"
        @pagination="getList"
    />

    <!-- 添加或修改仓储盘点对话框 -->
    <el-dialog v-model="open" :title="title" append-to-body width="800px">
      <el-form ref="stockCheckRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="仓库ID" prop="warehouseId">
          <template #default="scope">
            <el-tree-select
                v-model="form.warehouseId"
                :data="warehouseOptions"
                value-key="id"
                check-strictly
                :render-after-expand="false"
                :props="{ value: 'id', label: 'name', children: 'children' }"
            />
          </template>
        </el-form-item>
        <el-form-item label="盘点人" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入盘点人"/>
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-input v-model="form.state" placeholder="请输入状态"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入内容" type="textarea"/>
        </el-form-item>
        <el-divider content-position="center">库存盘点信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-form-item label="商品库存" v-if="showAddDetail">
              <DictSearchWmsGoodsStock :dictName="dictGoods.dictName" :dictType="dictGoods.dictType"
                          :isSingle="dictGoods.isSingle" :params="dictGoods.params"
                          @selectd="dictSelectdGoodsLine">
              </DictSearchWmsGoodsStock>
            </el-form-item>
          </el-col>
          <el-col :span="1.5">
            <el-button icon="Plus" type="primary" @click="toggleAddDetail" :disabled="addButtonDisabled">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-form-item label="添加物品明细" v-if="showAddDetail">
              <DictSearch :dictName="dictGoods1.dictName" :dictType="dictGoods1.dictType"
                          :isSingle="dictGoods1.isSingle" :params="dictGoods1.params"
                          @selectd="dictSelectdGoodsLine1">
              </DictSearch>
            </el-form-item>
          </el-col>
          <el-col :span="1.5">
            <el-button icon="Delete" type="danger" @click="handleDeleteWmsGoodsStockCheckLine">删除</el-button>
          </el-col>
        </el-row>
        <el-table ref="wmsGoodsStockCheckLine" :data="wmsGoodsStockCheckLineList"
                  :row-class-name="rowWmsGoodsStockCheckLineIndex" @selection-change="handleWmsGoodsStockCheckLineSelectionChange">
          <el-table-column align="center" type="selection" width="50"/>
          <el-table-column align="center" label="序号" prop="index" width="50"/>
          <el-table-column label="排序" prop="id" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.orderNum" placeholder="排序"/>
            </template>
          </el-table-column>
          <el-table-column label="物品编码" prop="goodsCode" width="150">
          </el-table-column>
          <el-table-column label="产品名称" align="center" prop="goodsName"/>
          <el-table-column label="单位" prop="measureUnit" width="150">
          </el-table-column>
          <el-table-column label="在库数量" prop="quantity" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.quantity" placeholder="请输入在库数量"/>
            </template>
          </el-table-column>
          <el-table-column label="入库批次号" prop="batchCode" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.batchCode" placeholder="请输入入库批次号"/>
            </template>
          </el-table-column>
          <el-table-column label="仓库ID" prop="warehouseId" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.warehouseId" placeholder="请输入仓库ID"/>
            </template>
          </el-table-column>
          <el-table-column label="库位ID" prop="areaId" width="150">
          </el-table-column>
          <el-table-column label="供应商ID" prop="supplierId" width="150">
          </el-table-column>
          <el-table-column label="生产厂商id" prop="manufacturerId" width="150">
          </el-table-column>
          <el-table-column label="库存有效期" prop="expireDate" width="240">
          </el-table-column>
          <el-table-column label="创建者" prop="createBy" width="150">
          </el-table-column>
          <el-table-column label="入库时间" prop="createTime" width="240">
          </el-table-column>
          <el-table-column label="更新者" prop="updateBy" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.updateBy" placeholder="请输入更新者"/>
            </template>
          </el-table-column>
          <el-table-column label="更新时间" prop="updateTime" width="240">
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script name="StockCheck" setup>
import {addStockCheck, delStockCheck, getStockCheck, listStockCheck, updateStockCheck} from "@/api/wms/stockCheck";
import {computed, reactive, ref, watch} from "vue";

import {listWarehouse} from "@/api/wms/warehouse";
const {proxy} = getCurrentInstance();
const {
  sys_state
} = proxy.useDict('sys_state');

const route = useRoute();
const pageLabel = reactive({
  partnerName: "",
  receivableMoney: "",
  selfWhName:"",
  otherWhName:"",
  money: ""
});
const stockCheckList = ref([]);
const wmsGoodsStockCheckLineList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedWmsGoodsStockCheckLine = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeUpdateTime = ref([]);
const warehouseOptions = ref([]);
const addButtonDisabled = computed(() => {
return !form.value.warehouseId;
 });
const computedWarehouseId = computed(() => {
  return form.value.warehouseId || 0; // 你可以在这里应用任何逻辑来处理值
});

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    warehouseId: computedWarehouseId,
    userId: null,
    state: null,
    updateTime: null
  },
  rules: {
    warehouseId: [
      {required: true, message: "仓库ID不能为空", trigger: "blur"}
    ],
  }
});

const {queryParams, form, rules} = toRefs(data);
const showAddDetail = ref(false);

function getGoodsTree(warehouseId) {
  listWarehouse({parentId: warehouseId}).then(response => {
    warehouseOptions.value = proxy.handleTree(response.data, "id");
  });
}



function toggleAddDetail() {
  // 点击 "新增一行" 按钮时切换显示状态
  showAddDetail.value = !showAddDetail.value;
}

const dictGoods = reactive({
  dictName: "商品库存查找", // 设置单据编号查找的字典名称
  dictType: "wms_goods_stock",
  isSingle: false,
  params: {
    warehouseId : computedWarehouseId
  }
});

const dictGoods1 = reactive({
  dictName: "物品明细查找", // 设置单据编号查找的字典名称
  dictType: "md_goods_line",
  isSingle: false,
  params: {}
});

function dictSelectdGoodsLine1(dicts) {
  dicts.forEach(function (item) {
    let line = {};
    line.goodsCode = item.dictValue;
    line.goodsName = item.dictLabel;
    line.price = item.param1;
    line.attrValue = item.param2;
    line.measureUnit = item.param3;
    handleAddWmsGoodsStockCheckLine(line);
  });
}
function dictSelectdGoodsLine(dicts) {
  dicts.forEach(function (item) {
    let line = {};
    line.goodsName = item.dictLabel;
    line.goodsCode = item.dictValue;
    line.id = item.param1;
    line.measureUnit = item.param2;
    line.batchCode = item.param3;
    line.warehouseId = item.param4;
    line.areaId = item.param5;
    line.supplierId = item.param6;
    line.manufacturerId = item.param7;
    line.quantity = item.param8;
    line.expireDate= item.param9;
    line.remark = item.param10;
    line.createBy = item.param11;
    line.createTime = item.param12;
    line.updateBy = item.param13;
    line.updateTime = item.param14;
    handleAddWmsGoodsStockCheckLine(line);
  });
}


/** 查询仓储盘点列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeUpdateTime && '' != daterangeUpdateTime) {
    queryParams.value.params["beginUpdateTime"] = daterangeUpdateTime.value[0];
    queryParams.value.params["endUpdateTime"] = daterangeUpdateTime.value[1];
  }
  listStockCheck(queryParams.value).then(response => {
    stockCheckList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });

  getGoodsTree(queryParams.value.warehouseId);
  loading.value = false;
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    warehouseId: null,
    userId: null,
    state: route.query.state,
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  wmsGoodsStockCheckLineList.value = [];
  proxy.resetForm("stockCheckRef");
}


/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeUpdateTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加仓储盘点";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getStockCheck(_id).then(response => {
    form.value = response.data;
    wmsGoodsStockCheckLineList.value = response.data.wmsGoodsStockCheckLineList;
    open.value = true;
    title.value = "修改仓储盘点" + _id;
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["stockCheckRef"].validate(valid => {
    if (valid) {
      form.value.wmsGoodsStockCheckLineList = wmsGoodsStockCheckLineList.value;
      if (form.value.id != null) {
        updateStockCheck(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addStockCheck(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除仓储盘点编号为"' + _ids + '"的数据项？').then(function () {
    return delStockCheck(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 库存盘点序号 */
function rowWmsGoodsStockCheckLineIndex({row, rowIndex}) {
  row.index = rowIndex + 1;
}

/** 库存盘点添加按钮操作 */
function handleAddWmsGoodsStockCheckLine(row) {
  let obj = {};
  obj.orderNum = row.id;
  obj.goodsCode = row.goodsCode;
  obj.measureUnit = row.measureUnit;
  obj.goodsName = row.goodsName;
  obj.batchCode = row.batchCode;
  obj.warehouseId = row.warehouseId;
  obj.areaId = row.areaId;
  obj.supplierId = row.supplierId;
  obj.manufacturerId = row.manufacturerId;
  obj.quantity = row.quantity;
  obj.expireDate = row.expireDate;
  obj.remark = row.remark;
  obj.createBy = row.createBy;
  obj.createTime = row.createTime;
  obj.updateBy = row.updateBy;
  obj.updateTime = row.updateTime;
  wmsGoodsStockCheckLineList.value.push(obj);
}

/** 库存盘点删除按钮操作 */
function handleDeleteWmsGoodsStockCheckLine() {
  if (checkedWmsGoodsStockCheckLine.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的库存盘点数据");
  } else {
    const wmsGoodsStockCheckLines = wmsGoodsStockCheckLineList.value;
    const checkedWmsGoodsStockCheckLines = checkedWmsGoodsStockCheckLine.value;
    wmsGoodsStockCheckLineList.value = wmsGoodsStockCheckLines.filter(function (item) {
      return checkedWmsGoodsStockCheckLines.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handleWmsGoodsStockCheckLineSelectionChange(selection) {
  checkedWmsGoodsStockCheckLine.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('wms/stockCheck/export', {
    ...queryParams.value
  }, `stockCheck_${new Date().getTime()}.xlsx`)
}
function initPage() {
  queryParams.value = route.query;
  if (queryParams.value.state == 1 || queryParams.value.state == 3 || queryParams.value.state == 14) {
    pageLabel.partnerName = "客户";
  } else if (queryParams.value.state == 0 || queryParams.value.state == 4) {
    pageLabel.partnerName = "供应商";

  } else if (queryParams.value.state == 100) {
    pageLabel.partnerName = "客 户";
  }
}
// 监听form.warehouseId的变化
watch(form.warehouseId, (newValue) => {
  if (newValue !== null) {
    // 当warehouseId发生变化时，将其值传递给queryParams中的warehouseId
    queryParams.warehouseId = newValue;
  }
});
initPage();
getList();
</script>
